<template>
	<view class="statistics">
		<!-- 时间选择 -->
		<view class="time-selector">
			<view class="time-tabs">
				<text 
					class="time-tab" 
					:class="{ active: timeRange === 'month' }"
					@tap="changeTimeRange('month')"
				>本月</text>
				<text 
					class="time-tab" 
					:class="{ active: timeRange === 'year' }"
					@tap="changeTimeRange('year')"
				>本年</text>
				<text 
					class="time-tab" 
					:class="{ active: timeRange === 'custom' }"
					@tap="changeTimeRange('custom')"
				>自定义</text>
			</view>
			
			<view class="time-display" v-if="timeRange !== 'custom'">
				<text>{{ currentTimeText }}</text>
			</view>
			
			<view class="custom-time" v-else>
				<picker mode="date" :value="customStartDate" @change="onStartDateChange">
					<view class="date-picker">
						<text>{{ customStartDate }}</text>
					</view>
				</picker>
				<text class="time-divider">至</text>
				<picker mode="date" :value="customEndDate" @change="onEndDateChange">
					<view class="date-picker">
						<text>{{ customEndDate }}</text>
					</view>
				</picker>
			</view>
		</view>

		<!-- 总览卡片 -->
		<view class="overview-cards">
			<view class="card income-card">
				<text class="card-label">总收入</text>
				<text class="card-value">¥{{ stats.income.toFixed(2) }}</text>
			</view>
			<view class="card expense-card">
				<text class="card-label">总支出</text>
				<text class="card-value">¥{{ stats.expense.toFixed(2) }}</text>
			</view>
			<view class="card balance-card">
				<text class="card-label">结余</text>
				<text class="card-value" :class="stats.balance >= 0 ? 'positive' : 'negative'">
					¥{{ stats.balance.toFixed(2) }}
				</text>
			</view>
		</view>

		<!-- 分类统计 -->
		<view class="category-stats">
			<view class="stats-header">
				<text class="stats-title">分类统计</text>
				<view class="type-switch">
					<text 
						class="switch-item" 
						:class="{ active: statsType === '支出' }"
						@tap="switchStatsType('支出')"
					>支出</text>
					<text 
						class="switch-item" 
						:class="{ active: statsType === '收入' }"
						@tap="switchStatsType('收入')"
					>收入</text>
				</view>
			</view>

			<view class="stats-list">
				<view v-if="currentCategoryStats.length === 0" class="empty-stats">
					<text>暂无数据</text>
				</view>
				
				<view 
					v-for="(item, index) in currentCategoryStats" 
					:key="index"
					class="stats-item"
				>
					<view class="stats-left">
						<view class="stats-icon">
							<text class="iconfont" :class="item._id.category_icon || 'icon-qita'"></text>
						</view>
						<view class="stats-info">
							<text class="stats-name">{{ item._id.category_name || '未分类' }}</text>
							<text class="stats-count">{{ item.count }}笔</text>
						</view>
					</view>
					<view class="stats-right">
						<text class="stats-amount">¥{{ item.total.toFixed(2) }}</text>
						<text class="stats-percent">{{ getPercent(item.total) }}%</text>
					</view>
					<!-- 进度条 -->
					<view class="progress-bar">
						<view class="progress-fill" :style="{ width: getPercent(item.total) + '%' }"></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			timeRange: 'month', // month, year, custom
			customStartDate: '',
			customEndDate: '',
			stats: {
				income: 0,
				expense: 0,
				balance: 0,
				categoryStats: []
			},
			statsType: '支出' // 支出/收入
		}
	},
	computed: {
		// 当前时间文本
		currentTimeText() {
			if (this.timeRange === 'month') {
				const date = new Date()
				return `${date.getFullYear()}年${date.getMonth() + 1}月`
			} else if (this.timeRange === 'year') {
				const date = new Date()
				return `${date.getFullYear()}年`
			}
			return ''
		},
		
		// 当前分类统计
		currentCategoryStats() {
			return this.stats.categoryStats
				.filter(item => item._id.type === this.statsType)
				.sort((a, b) => b.total - a.total)
		},
		
		// 当前类型总额
		currentTypeTotal() {
			return this.currentCategoryStats.reduce((sum, item) => sum + item.total, 0)
		}
	},
	onLoad() {
		this.initCustomDate()
		this.loadStatistics()
	},
	methods: {
		// 初始化自定义日期
		initCustomDate() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, '0')
			this.customEndDate = `${year}-${month}-${String(now.getDate()).padStart(2, '0')}`
			this.customStartDate = `${year}-${month}-01`
		},
		
		// 切换时间范围
		changeTimeRange(range) {
			this.timeRange = range
			this.loadStatistics()
		},
		
		// 开始日期改变
		onStartDateChange(e) {
			this.customStartDate = e.detail.value
			this.loadStatistics()
		},
		
		// 结束日期改变
		onEndDateChange(e) {
			this.customEndDate = e.detail.value
			this.loadStatistics()
		},
		
		// 切换统计类型
		switchStatsType(type) {
			this.statsType = type
		},
		
		// 加载统计数据
		async loadStatistics() {
			try {
				const { startDate, endDate } = this.getDateRange()
				
				const accountObj = uniCloud.importObject('account')
				const res = await accountObj.getStatistics({
					startDate,
					endDate
				})
				
				if (res.code === 0) {
					this.stats = res.data
				}
			} catch (e) {
				console.error('加载统计失败', e)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},
		
		// 获取日期范围
		getDateRange() {
			if (this.timeRange === 'month') {
				const now = new Date()
				const year = now.getFullYear()
				const month = now.getMonth()
				const startDate = `${year}-${String(month + 1).padStart(2, '0')}-01`
				const endDate = `${year}-${String(month + 1).padStart(2, '0')}-${String(this.getMonthDays(year, month)).padStart(2, '0')}`
				return { startDate, endDate }
			} else if (this.timeRange === 'year') {
				const year = new Date().getFullYear()
				return {
					startDate: `${year}-01-01`,
					endDate: `${year}-12-31`
				}
			} else {
				return {
					startDate: this.customStartDate,
					endDate: this.customEndDate
				}
			}
		},
		
		// 获取月份天数
		getMonthDays(year, month) {
			return new Date(year, month + 1, 0).getDate()
		},
		
		// 计算百分比
		getPercent(amount) {
			if (this.currentTypeTotal === 0) return 0
			return Math.round((amount / this.currentTypeTotal) * 100)
		}
	}
}
</script>

<style scoped>
.statistics {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 40rpx;
}

/* 时间选择 */
.time-selector {
	background-color: #fff;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.time-tabs {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.time-tab {
	flex: 1;
	text-align: center;
	padding: 12rpx 0;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #666;
	background-color: #f5f5f5;
	transition: all 0.3s;
}

.time-tab.active {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
}

.time-display {
	text-align: center;
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
	padding: 20rpx 0;
}

.custom-time {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 20rpx;
}

.date-picker {
	padding: 12rpx 24rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
}

.time-divider {
	font-size: 28rpx;
	color: #999;
}

/* 总览卡片 */
.overview-cards {
	display: flex;
	gap: 20rpx;
	padding: 0 20rpx;
	margin-bottom: 20rpx;
}

.card {
	flex: 1;
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.income-card {
	border-top: 4rpx solid #52c41a;
}

.expense-card {
	border-top: 4rpx solid #ff4d4f;
}

.balance-card {
	border-top: 4rpx solid #667eea;
}

.card-label {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 10rpx;
}

.card-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.card-value.positive {
	color: #52c41a;
}

.card-value.negative {
	color: #ff4d4f;
}

/* 分类统计 */
.category-stats {
	background-color: #fff;
	margin: 0 20rpx;
	border-radius: 16rpx;
	padding: 30rpx 20rpx;
}

.stats-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
}

.stats-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.type-switch {
	display: flex;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	overflow: hidden;
}

.switch-item {
	padding: 8rpx 24rpx;
	font-size: 24rpx;
	color: #666;
	transition: all 0.3s;
}

.switch-item.active {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
}

.stats-list {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.empty-stats {
	text-align: center;
	padding: 60rpx 0;
	font-size: 28rpx;
	color: #999;
}

.stats-item {
	position: relative;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background-color: #f8f8f8;
	border-radius: 12rpx;
}

.stats-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.stats-icon {
	width: 70rpx;
	height: 70rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.stats-icon .iconfont {
	font-size: 36rpx;
	color: #fff;
}

.stats-info {
	display: flex;
	flex-direction: column;
}

.stats-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 6rpx;
}

.stats-count {
	font-size: 24rpx;
	color: #999;
}

.stats-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.stats-amount {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 6rpx;
}

.stats-percent {
	font-size: 24rpx;
	color: #667eea;
}

.progress-bar {
	position: absolute;
	left: 0;
	bottom: 0;
	width: 100%;
	height: 4rpx;
	background-color: #e8e8e8;
	border-radius: 0 0 12rpx 12rpx;
	overflow: hidden;
}

.progress-fill {
	height: 100%;
	background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
	transition: width 0.3s;
}
</style>

